package com.tsmti.lab.controller.system;

import com.tsmti.core.common.constant.RedisConstants;
import com.tsmti.core.common.controller.BaseCrudController;
import com.tsmti.core.common.model.AjaxJson;
import com.tsmti.core.common.query.data.Queryable;
import com.tsmti.core.util.ConvertUtil;
import com.tsmti.core.util.StringUtils;
import com.tsmti.shiro.annotation.RequiresPathPermission;
import com.tsmti.system.entity.*;
import com.tsmti.system.service.*;
import com.tsmti.util.DictionaryUtils;
import com.tsmti.util.UserUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @Package：com.tsmti.lab.controller.system
 * @Class：UserController
 * @Description： TODO
 * @Author：zcw
 * @Date：Created in 2018/3/14 17:15
 * @Company:
 * @Version：
 * @Modified By:
 */
@Controller
@RequestMapping("/system/user")
@RequiresPathPermission("sys:user")
public class UserController extends BaseCrudController<User,Long> {

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private UserOrganizationService userOrganizationService;

    @Override
    public String showCreate(User user, Model model, HttpServletRequest request, HttpServletResponse response) {
        model.addAttribute("nowOrgId",UserUtils.getOrgId());
        return display("create");
    }
    @Override
    public String showUpdate(User user, Model model, HttpServletRequest request, HttpServletResponse response) {
        model.addAttribute("nowOrgId",UserUtils.getOrgId());
        return "";
    }

    @RequestMapping(value = "{id}/changePassword", method = RequestMethod.GET)
    public String changePassword(@PathVariable("id") Long id, Model model, HttpServletRequest request,
                                 HttpServletResponse response) {
        User user = userService.get(id);
        model.addAttribute("data", user);
        return display("changePassword");
    }

    @RequestMapping(value = "{id}/changePassword", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson changePassword(@PathVariable("id") Long id, HttpServletRequest request,
                                   HttpServletResponse response) {
        AjaxJson ajaxJson = AjaxJson.success("密码修改成功");
        try {
            String password = request.getParameter("password");
            userService.changePassword(id, password);
        } catch (Exception e) {
            logger.error("密码修改失败",e);
            ajaxJson = AjaxJson.fail("密码修改失败");
        }
        return ajaxJson;
    }


    @Override
    public void preAjaxList(Queryable queryable, DetachedCriteria detachedCriteria, HttpServletRequest request,
                            HttpServletResponse response) {
        List<DataDictionary> dictList = DictionaryUtils.getDictList("sex");
        // 子查询
        Long organizationId = ConvertUtil.getLongValue(request.getParameter("organizationid"));
        if (organizationId > 0) {
            DetachedCriteria userOrganizationCriteria = DetachedCriteria.forClass(UserOrganization.class);
            userOrganizationCriteria.setProjection(Property.forName("user.id"));
            userOrganizationCriteria.add(Restrictions.eq("organization.id", organizationId));
            detachedCriteria.add(Property.forName("id").in(userOrganizationCriteria));
        }

    }

    @Override
    public void preEdit(User user, Model model, HttpServletRequest request, HttpServletResponse response) {
        // 查询所有的角色List
        List<Role> allRoles = roleService.list();
        request.setAttribute("allRoles", allRoles);
        if (user.getId() != null) {
            // 查找关联角色
            List<Role> userRoles = roleService.findListByUserId(user.getId());
            request.setAttribute("roleIdList", userRoles);
            List<Organization> organizations = organizationService.findListByUserId(user.getId());
            StringBuilder organizationIds = new StringBuilder();
            StringBuilder organizationNames = new StringBuilder();
            for (Organization organization : organizations) {
                if (!StringUtils.isEmpty(organizationIds)) {
                    organizationIds.append(",");
                    organizationNames.append(",");
                }
                Long organizationId = organization.getId();
                organizationIds.append(organizationId);
                organizationNames.append(organization.getName());
            }
            request.setAttribute("organizationIds", organizationIds.toString());
            request.setAttribute("organizationNames", organizationNames.toString());
        }
    }

    @Override
    public void preSave(User entity, HttpServletRequest request, HttpServletResponse response) {

    }
    @Override
    public void afterSave(User entity, HttpServletRequest request, HttpServletResponse response) {
        // 删除角色关联
        String [] roleIdList = request.getParameterValues("roleIdList");

        if (roleIdList != null && roleIdList.length > 0) {
            if(entity != null && entity.getId() != null){
                userRoleService.removeAllByProperty("userId", entity.getId());
            }
            List<UserRole> userRoleList = new ArrayList<UserRole>();
            for (String roleId : roleIdList) {
                UserRole userRole = new UserRole();
                userRole.setUserId(entity.getId());
                userRole.setRoleId(ConvertUtil.getLongValue(roleId));
                userRoleList.add(userRole);
            }
            userRoleService.saveAll(userRoleList);
        }

        // 删除部门关联
        String organizationIdListStr = request.getParameter("organizationIds");
        String[] organizationIdList = organizationIdListStr.split(",");
        if (organizationIdList != null && organizationIdList.length > 0) {
            if(entity != null && entity.getId() != null){
                userOrganizationService.removeAllByProperty("userId", entity.getId());
            }
            List<UserOrganization> userOrganizationList = new ArrayList<UserOrganization>();
            for (String organizationId : organizationIdList) {
                UserOrganization userOrganization = new UserOrganization();
                userOrganization.setUserId(entity.getId());
                userOrganization.setOrganizationId(ConvertUtil.getLongValue(organizationId));
                userOrganizationList.add(userOrganization);
            }
            userOrganizationService.saveAll(userOrganizationList);
        }
    }


    @RequestMapping(value = "info", method = RequestMethod.GET)
    public String info(@RequestParam(required = false) String id, Model model, HttpServletRequest request,
                       HttpServletResponse response) {
        User user = userService.get(id);
        model.addAttribute("data", user);
        return display("info");
    }
    @RequestMapping(value = "/getUserInfo/{username}", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson getUserInfo(@PathVariable("username") String username, HttpServletRequest request,
                                HttpServletResponse response) {
        User user = userService.get("userName", username);
        if(user == null){
            return AjaxJson.fail("用户不存在");
        }
        List<Organization> organizations = organizationService.findListByUserId(user.getId());
        StringBuilder orgIds = new StringBuilder();
        for(Organization organization:organizations){
            if (orgIds.length() >0) {
                orgIds.append(",");
            }
            orgIds.append(organization.getCode());
        }
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.setRet(AjaxJson.RET_SUCCESS);
        ajaxJson.setMsg("成功!");
        ajaxJson.put("username", user.getUserName());
        ajaxJson.put("realname", user.getRealName());
        ajaxJson.put("organizations",orgIds);
        return ajaxJson;
    }

    /**
     * 缓存
     */
    @Override
    public void loadCache(){
        UserUtils.reLoadCache();
    }

}
